import datetime
import django.core.paginator as p
import django.http as h
import django.shortcuts as s
import django.template as t
import ourcity.news.models as nm
import urllib as u

def reports(request):
    context = t.RequestContext(request)
    reports = nm.News.objects.reports()
    context['years'] = reversed([str(x.year) for x in 
        reports.dates('pub_date', 'year')])
    query_year = request.GET.get('year')
    if query_year:
        try:
            year = int(query_year)
        except ValueError:
            pass
        else:
            context['query_year'] = query_year
            reports = reports.filter(pub_date__year=year)
    paginator = p.Paginator(reports, 6) # Show 6 reports per page
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    # If page request (9999) is out of range, deliver last page of results.
    try:
        reports = paginator.page(page)
    except (p.EmptyPage, p.InvalidPage):
        reports = paginator.page(paginator.num_pages)

    if context.get('query_year'):
        context['url_params'] = u.urlencode({'year': query_year})
        context['reports'] = reports
        template = t.loader.get_template('news/report_archives.html')
        return h.HttpResponse(template.render(context))
    context['reports'] = reports
    template = t.loader.get_template('news/reports.html')
    return h.HttpResponse(template.render(context))

def report(request, id):
    context = t.RequestContext(request)
    context['years'] = reversed([x.year for x in 
        nm.News.objects.reports().dates('pub_date', 'year')])
    report = s.get_object_or_404(nm.News, id=id)
    if report.type.name != 'Report':
        raise h.Http404
    context['report'] = report
    if not report.active:
        context['not_published'] = True
    template = t.loader.get_template('news/report.html')
    return h.HttpResponse(template.render(context))

def blog(request):
    context = t.RequestContext(request)
    posts = nm.News.objects.posts()
    context['months'] = reversed(posts.dates('pub_date', 'month'))
    query_month = request.GET.get('month')
    if query_month:
        try:
            year = int(query_month[:4])
            month = int(query_month[4:])
        except ValueError:
            pass
        else:
            context['query_month'] = datetime.date(year, month, 1)
            posts = posts.filter(pub_date__month=month, pub_date__year=year)
    paginator = p.Paginator(posts, 6) # Show 6 posts per page
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    # If page request (9999) is out of range, deliver last page of results.
    try:
        posts = paginator.page(page)
    except (p.EmptyPage, p.InvalidPage):
        posts = paginator.page(paginator.num_pages)

    if context.get('query_month'):
        context['url_params'] = u.urlencode({'month': query_month})
        context['posts'] = posts
        template = t.loader.get_template('news/blog_archives.html')
        return h.HttpResponse(template.render(context))
    context['posts'] = posts
    template = t.loader.get_template('news/blog.html')
    return h.HttpResponse(template.render(context))

def post(request, id):
    context = t.RequestContext(request)
    posts = nm.News.objects.posts()
    context['months'] = reversed(posts.dates('pub_date', 'month'))
    post = s.get_object_or_404(nm.News, id=id)
    if post.type.name != 'Post':
        raise h.Http404
    context['post'] = post
    if post.pub_date:
        try:
            context['older'] = posts.filter(pub_date__lt=post.pub_date)[0]
        except IndexError:
            context['older'] = None
        try:
            context['newer'] = posts.filter(pub_date__gt=post.pub_date
                    ).order_by('pub_date')[0]
        except IndexError:
            context['newer'] = None
    if not post.active:
        context['not_published'] = True
    template = t.loader.get_template('news/post.html')
    return h.HttpResponse(template.render(context))


